import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Input, message, Select, Form, Tabs, Button } from 'antd';
import services from '../../../services/api';
import Base from './base';
import API from './api';
import './index.less';

const { TabPane } = Tabs;

class DataSourceAdd extends Component {
  constructor(props) {
    super(props);
    this.state = {
      activeKey: '1',
    };
    this.form = null;
    this.api = 'dataSourceManage';
    this.id = props.match.params.id;
    this.tabList = [
      {
        key: '1',
        title: '搜索API',
        preKey: 'searchApi',
      },
      {
        key: '2',
        title: '计算API',
        preKey: 'calcApi',
      },
    ];
  }

  componentDidMount() {
    if (this.id) {
      this.getDetail();
    }
  }

  /**获取详情 */
  getDetail = () => {
    services[this.api].queryOne({ id: Number(this.id) }).then((data) => {
      if (data.code === '0') {
        this.setState({
          detail: data.data,
        });
        const detail = {};
        Object.keys(data.data).forEach((item) => {
          if (data.data[item] instanceof Object) {
            Object.keys(data.data[item]).forEach((it) => {
              if (it !== 'id') {
                detail[item + '-' + it] = data.data[item][it];
              }
            });
          } else {
            if (item !== 'id') {
              detail[item] = data.data[item];
            }
          }
        });
        console.log(detail);
        // data.data.searchApi
        Object.keys(this.props.form.getFieldsValue()).forEach((key) => {
          const obj = {};
          obj[key] = detail[key] || null;
          this.props.form.setFieldsValue(obj);
        });
      } else {
        message.error(data.msg);
      }
    });
  };

  handleSubmit = () => {
    this.props.form.validateFields((err, values) => {
      console.log(values);
      if (!err) {
        const params = {};
        Object.keys(values).forEach((item) => {
          const [first, second] = item.split('-');
          if (second) {
            if (params[first]) {
              params[first][second] = values[item];
            } else {
              params[first] = {};
              params[first][second] = values[item];
            }
          } else {
            params[first] = values[item];
          }
        });

        let save = 'add';
        if (this.id) {
          params.id = Number(this.id);
          save = 'update';
          params.calcApi.id = this.state.detail.calcApi.id;
          params.calcApi.code = this.state.detail.calcApi.code;
          params.searchApi.id = this.state.detail.searchApi.id;
          params.searchApi.code = this.state.detail.searchApi.code;
          delete params.code;
        }
        services[this.api][save](params).then((res) => {
          if (res.code === '0') {
            message.success(res.msg);
            this.props.history.push('/system/dataSource');
          } else {
            message.error(res.msg);
          }
        });
      }
    });
  };

  render() {
    const { activeKey } = this.state;
    return (
      <div className='dataSource-content'>
        <div className='stretegy-wp tantuer-form ' id='intro-farm' style={{ position: 'relative' }}>
          <Form className='stretegy-wp-form' autoComplete='off'>
            <Base {...this.props} />
            <Tabs activeKey={activeKey} onChange={(activeKey) => this.setState({ activeKey })}>
              {this.tabList.map(({ key, title, preKey }) => (
                <TabPane tab={title} key={key}>
                  <API {...this.props} preKey={preKey} isValidate={key === '1'} />
                </TabPane>
              ))}
            </Tabs>
            <div className='form-btn'>
              <Button className='login-form-button' onClick={() => this.props.history.push('/system/dataSource')}>
                取消
              </Button>
              <Button type='primary' onClick={this.handleSubmit} className='login-form-button' autoFocus={true}>
                确定
              </Button>
            </div>
          </Form>
        </div>
      </div>
    );
  }
}
function mapStateToProps(state) {
  const { api_protocol_type, api_method_type, dataSource_type = [] } = state.code;
  return {
    api_protocol_type,
    api_method_type,
    dataSource_type,
  };
}
export default connect(mapStateToProps)(Form.create()(DataSourceAdd));
